<template>
  <el-row>
    <el-col :span="16">
      <el-table
        :data="tableData.data"
        ref="tableRef"
        height="500"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column prop="Product " label="Product" min-width="250">
          <template #default="scope">
            <OrderProduct :scope="scope" />
          </template>
        </el-table-column>
        <el-table-column align="right" prop="Cost" label="Cost ">
          <p class="p-22214">
            <strong class="p-22214">1231 </strong>
            <span class="p13222"> USD </span>
          </p>
        </el-table-column>
        <el-table-column prop="Quantity" label="Quantity">
          <template #default="scope">
            <strong class="p-22214">{{ scope.row.input2 }} </strong>
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          prop="NumberOfReissues"
          label="Number of reissues"
        >
          <template #default="scope">
            <strong class="p-22214">
              <el-input
                :ref="!scope.row.disabled ? setItemRef : ''"
                :disabled="scope.row.disabled"
                type="number"
                class="reissuesInput refBorder"
                v-model="scope.row.input3"
                @input="(e) => onMaxInput(e, scope.row.input2, scope.$index)"
              />
              <span>/1</span>
            </strong>
            <div
              class="cRed"
              v-if="!scope.row.disabled && scope.row.input3 === ''"
            >
              Please enter the quantity
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="stepForm.type !== 'Resended'"
          width="150"
          prop="AmountRefunded"
          label="Amount refunded"
        >
          <template #default="scope">
            <el-input
              class="reissuesInput"
              type="number"
              disabled
              v-model="scope.row.input2"
            />
            <span class="p13222"> USD </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="tbTxt">
        Shipping cost:
        <el-input type="number" class="reissuesInput" v-model="input1" />
        <span class="p13222"> USD </span>
        <p class="p12red">Refundable up to 00.00 USD</p>
      </div>
    </el-col>
    <el-col :span="8" class="span8">
      <div class="formTop" v-if="stepForm.type !== 'Resended'">
        <el-row class="mb-4 spaceBetween">
          <div class="p13777">Refund amount:</div>
          <div>
            <strong class="p-22214">1231 </strong>
            <span class="p13222"> USD </span>
          </div>
        </el-row>
        <el-row class="mb-4 spaceBetween">
          <div class="p13777">Shipping cost:</div>
          <div>
            <strong class="p-22214">1231 </strong>
            <span class="p13222"> USD </span>
          </div>
        </el-row>
        <el-row class="mb-4 spaceBetween">
          <div class="p13777">Discount:</div>
          <div>
            <strong class="p-22214">1231 </strong>
            <span class="p13222"> USD </span>
          </div>
        </el-row>
        <el-row class="mb-4 spaceBetween">
          <div class="p13777">Total:</div>
          <div>
            <strong class="p-22214">1231 </strong>
            <span class="p13222"> USD </span>
          </div>
        </el-row>
      </div>
      <el-form
        label-position="top"
        label-width="100px"
        :model="form"
        style="max-width: 460px"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="Activity form" prop="desc">
          <el-input
            maxlength="1000"
            show-word-limit
            v-model="form.desc"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="appendix">
          <!-- 上传 -->
          <el-upload
            class="upload-demo"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-error="handleError"
          >
            <el-button type="default">
              Upload<el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button
            type="danger"
            :disabled="!multipleSelection.length"
            @click="submitForm(ruleFormRef)"
            >Submit</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import OrderProduct from "@/components/OrderTable/orderProduct.vue";
import type { FormInstance, FormRules } from "element-plus";

import { ref, reactive, onMounted, inject } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import type { UploadProps, UploadUserFile } from "element-plus";
const multipleSelection = ref([]);
const input1 = ref();
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
// const props = defineProps(["type"]);
import { ElTable } from "element-plus";
const stepForm = inject("stepForm");
console.log(stepForm, "stepForm");

const tableRef = ref<InstanceType<typeof ElTable>>();
const toggleSelection = (rows?: any) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      tableRef.value!.toggleRowSelection(row, undefined);
    });
  }
};

const fnDiffArr = (b) => {
  tableData.data.forEach((k) => {
    k.disabled = true;

    b.forEach((v) => {
      if (k.id === v.id) {
        k.disabled = false;
      }
    });
  });
};
onMounted(() => {
  // toggleSelection([tableData.data[0]]);
  // fnDiffArr([tableData.data[0]]);
});
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  fnDiffArr(val);
};
const form = reactive({
  desc: "",
  //   reason: "",
});

//
const itemRefs = [];
const setItemRef = (el) => {
  if (el) {
    if (!itemRefs.includes(el)) {
      itemRefs.push(el);
    }
  }
};
itemRefs.forEach((item) => {
  // item 即为对应的组件ref
  // 可通过 item 获取对应组件上的属性或方法
});

const rules = reactive<FormRules<RuleForm>>({
  desc: [
    { required: true, message: "Please input activity form", trigger: "blur" },
  ],
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let fTableData = tableData.data.filter((e) => !e.disabled && !e.input3);
      // if (fTableData.length > 0) ElMessage("请填写Number of reissues");
      console.log(itemRefs, "itemRefs");
      itemRefs.forEach((e) => {
        if (!e.input.value) {
          e.focus();
        }
      });
      // if (fTableData.length > 0) myInput.value.focus();
      if (fTableData.length > 0) return;
      router.push({
        path: "/Order/ScaleOrder/OrderDetails",
        query: {
          activeName: 2,
          type: stepForm.type,
          c: "okDisput",
        },
      });
    } else {
      ElMessage(`err`);
    }
  });
};
const tableData = reactive({
  data: [
    {
      id: 1,
      date: "2016-05-03",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input2: 231,
      input3: "",
      disabled: true,
    },
    {
      id: 2,

      date: "2016-05-02",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input2: 123,
      input3: "",
      disabled: true,
    },
    {
      id: 3,

      date: "2016-05-04",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input3: "",
      input2: 1,
      disabled: true,
    },
    {
      id: 4,

      date: "2016-05-01",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input3: "",
      input2: 231,
      disabled: true,
    },
    {
      id: 5,
      date: "2016-05-01",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input3: "",
      input2: 231,
      disabled: true,
    },
    {
      id: 6,

      date: "2016-05-01",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input3: "",
      input2: 231,
      disabled: true,
    },
    {
      id: 7,

      date: "2016-05-01",
      name: "Tom",
      address: "No. 189, Grove St, Los Angeles",
      input3: "",
      input2: 231,
      disabled: true,
    },
  ],
});
// 每行最大值
const onMaxInput = (e, v, i) => {
  if (e > v) tableData.data[i].input3 = v;
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
const handleError = (e: any) => {
  console.log(e);
  ElMessage("失败");
};
</script>
<style lang="scss" scoped>
// ::v-deep.refBorder {
//   .el-input__wrapper {
//     border: 1px solid #bc1f22 !important;
//   }
// }
// .upload-demo {
//   margin: 20px 0 10px 0;
// }
::v-deep
  .el-table--enable-row-hover
  .el-table__body
  tr:hover
  > td.el-table__cell {
  box-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.05);
  background: #fff !important;
  transition: all 0.5s;
}

::v-deep .el-table--enable-row-hover .el-table__body tr td {
  border-right: none;
  border-left: none;
}
::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  border-right: none !important;
  border-left: none !important;
}
::v-deep .el-checkbox__input {
  top: 2px;
}
::v-deep.el-table .el-table__cell {
  vertical-align: initial !important;
}
.reissuesInput {
  width: 58px;
  height: 24px;
  padding-right: 5px;
  padding-bottom: 2px;
}
.span8 {
  padding-left: 30px;
}
.tbTxt {
  text-align: right;
  margin: 10px 0;
}
.formTop {
  border-radius: 3px;
  border: 1px solid var(--unnamed, #dfe2e6);
  padding: 20px;
  margin-bottom: 20px;
  div {
    line-height: 38px;
  }
}
.cRed {
  color: #bc1f22;
  font-size: 12px;
}
</style>
